import { message } from 'antd'
import axios, { AxiosPromise, AxiosRequestConfig } from 'axios'

import { history } from '@/App'

// import { useSetRecoilState } from 'recoil'
// import { commonState } from '@/recoil'
// import { navigate } from '@/utils'
// import { getCookie, getStorage } from '..'
// import { filterNull } from './filterNull'
// const setIsLogin = useSetRecoilState(commonState.isLogin)
interface Request {
  <P, R>(
    url: string,
    params?: P,
    data?: P,
    config?: AxiosRequestConfig
  ): Promise<R>
}
//创建实例
const request = axios.create({
  timeout: 1000 * 30 // 30s后请求超时
})

request.interceptors.request.use(
  async function (config) {
    // const aToken = getStorage('token')
    // const aToken = getCookie('token')
    // // 更新token
    // if (aToken) {
    //   config.headers['Authorization'] = `Bearer ${aToken}`
    // }
    //TODO 全局loading，暂未完成
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截
request.interceptors.response.use(
  (response) => {
    const { data } = response
    const { code } = data
    switch (code) {
      // case 1000:
      case 200:
        // message.success(msg)
        return Promise.resolve(data)
      case 400:
        message.warning(data.msg)
        return Promise.reject(data)
      case 401:
        message.destroy()
        message.error('登录过期')
        const redirect = encodeURIComponent(
          `${window.location.pathname}${window.location.search}`
        )
        if (window.location.pathname !== '/login') {
          history.push(`/html/login?redirect=${redirect}`)
        } else {
          history.push(`/html/login`)
        }
        break

      case 5000:
        message.error(data.msg)
        return Promise.reject(data)
      default:
        // 失败
        // message.error(msg)
        return Promise.resolve(response)
    }
  },
  (error) => {
    console.log('requset error', error)
    // history.push('/register')
    if (error && error.response) {
      switch (error.response.status) {
        case 401:
          message.error('登录过期')
          const redirect = encodeURIComponent(
            `${window.location.pathname}${window.location.search}`
          )
          if (window.location.pathname !== '/login') {
            history.push(`/html/login?redirect=${redirect}`)
          } else {
            history.push(`/html/login`)
          }
          break
        case 403:
          //TODO 把当前的路由信息缓存，重新登陆后跳转到当前路由
          message.error('拒绝访问')
          break
        case 404:
          message.error('请求错误,未找到该资源')
          break
        case 405:
          message.error('请求方法未允许')
          break
        case 500:
          // window.location.href='/error500'
          break
        default:
          message.error(`连接错误${error.response.data.status}`)
      }
    } else {
      message.error('连接到服务器失败')
    }
    return Promise.reject(error)
  }
)

export default {
  get: function (url, params?) {
    return request({
      url,
      params,
      method: 'GET'
    })
  } as Request,
  post: function (url: string, data?) {
    return request({
      url,
      data,
      method: 'POST'
    })
  } as Request,
  put: function (url: string, data?) {
    return request({
      url,
      data,
      method: 'PUT'
    })
  } as Request,
  delete: function (url: string, params?) {
    return request({
      url,
      params,
      method: 'DELETE'
    })
  } as Request,
  request: function <P, R>(options: P): AxiosPromise<R> {
    return request(options)
  }
  // cancels // 切换路由之前 遍历cancels 执行方法 取消之前的请求
}
